package com.hehe.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hehe.boot.mapper.UserMapper;
import com.hehe.boot.pojo.Book;
import com.hehe.boot.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    private final BookService bookService;
    private static final Integer IDENTITY = 3;
    // 构造器注入
    public UserService(BookService bookService) {
        this.bookService = bookService;
    }

    @Transactional
    public Long register(String username,String password) {
        Book book = new Book();
        book.setIdentity(IDENTITY);
        book.setUsername(username);
        book.setPassword(password);
        User user = new User();
        this.save(user);
        book.setRelatedId(user.getId());
        this.bookService.save(book);
        user.setBookId(book.getId());
        this.updateById(user);
        return user.getId();
    }


    public Boolean setTelephone(Long userId, String telephone) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id",userId);
        updateWrapper.set("telephone",telephone);

        return this.update(updateWrapper);
    }

    public IPage<User> getProPage(int currentPage){
        // 构造分页条件
        Page<User> page = new Page<>(currentPage, 10);

        // 执行分页查询
        return this.page(page);
    }

    public IPage<User> getProPageLike(String query,int currentPage) {
        // 构造分页条件
        Page<User> page = new Page<>(currentPage, 10);

        // 构造查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", query);

        // 执行分页查询
        return page(page, queryWrapper);
    }

    public Boolean insertUser(User user) {
        user.setId(0L);
        boolean result = this.save(user);
        return result;
    }

    public Boolean updateUser(User user) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",user.getId());
        if (user.getName()!=null){
            updateWrapper.set("name",user.getName());
        }
        if (user!=null){
            updateWrapper.set("id_card",user.getIdCard());
        }
        if (user!=null){
            updateWrapper.set("telephone",user.getTelephone());
        }
        Boolean result = this.update(updateWrapper);
        return result;
    }

    public Boolean deleteUser(User user) {
        boolean result = this.removeById(user.getId());
        return result;
    }
}
